package com.wisedu.mobile.manage.controller;

import com.wisedu.mobile.common.AjaxResult;
import com.wisedu.mobile.common.BaseController;
import com.wisedu.mobile.common.constant.Constants;
import com.wisedu.mobile.common.domain.SysMenu;
import com.wisedu.mobile.common.domain.SysUser;
import com.wisedu.mobile.core.config.MobileCenterConfig;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hj
 * @Date: 2020/3/17 下午1:50
 */
@Controller
@RequestMapping("/manage")
public class IndexController extends BaseController<SysUser>{
    @Autowired
    MobileCenterConfig config;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response,ModelMap mmap)
    {
        mmap.put("sys", config);
        return "login";
    }


    /**
     * 跳转实时日志
     */
    @GetMapping("logging")
    public ModelAndView logging() {
        return new ModelAndView("logging.html","ipport",config.getApiCtx().substring(7));
    }

    /**
     * 跳转首页
     */
    @GetMapping("main")
    public String index(HttpServletRequest request, HttpServletResponse response,ModelMap mmap){
        AjaxResult result = post(request,"/auth/user",null);
        SysUser user = Json.fromJson(SysUser.class,Json.toJson(result.getData()));
        response.addCookie(new Cookie("uid",user.getId()));
        mmap.put("loginUser", user);
        mmap.put("sys", config);
        List<SysMenu> res = new ArrayList<>();
        for(SysMenu menu:user.getRoles().get(0).getMenus()){
            if(!Constants.MENUTYPE_API.equals(menu.getMenuType())&& !Strings.isEmpty(menu.getParentId())){
                res.add(menu);
            }
        }
        mmap.put("menuList",res);
        return "main";
    }

    @GetMapping("logout")
    public ModelAndView logout(HttpServletRequest request) {
        post(request,"/logout",null);
        return new ModelAndView("forward:/manage/login");
    }

}
